#include <tlnet\tlnetwork.h>

using namespace tlnet;

#ifdef _WIN32
#ifdef _DEBUG
	#define _CRTDBG_MAP_ALLOC
	#include <stdlib.h>
	#include <crtdbg.h>
	#undef THIS_FILE
	static char THIS_FILE[] = __FILE__;
	#define new       new( _NORMAL_BLOCK, __FILE__, __LINE__)
	#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif


void main(char *argv[], int argc) {
	NetworkManager *nm = new NetworkManager();
	Connection *c;
	char data[NETWORK_BUFLEN];

	c = nm->add();
	c->set("isListen", "true");
	c->set("port", "2244");
//	c->set("bindaddr", "localhost");		// optional, by default accepts connections from anywhere
	nm->start(c);

	printf("host is '%s'\n", c->get("host"));
	printf("hostip is '%s'\n", c->get("hostip"));

/*	c = nm.add();
	c->set("host", "google.com");
	c->set("port", "80");
	nm.start(c);
	c->write("GET /\n");
*/

	while(true) {
		// Wait for some network traffic to occur, or a timeout of 200 milliseconds
		nm->waitForReady();

		if(nm->isNew()) {
			// one or more new connections have been established
			while(c = nm->getNewConnection()) {
				printf("[%d] New connection added.\n", c->socket);

				printf("host is '%s'\n", c->get("host"));
				printf("hostip is '%s'\n", c->get("hostip"));
			}
		}
		else if(nm->isData()) {
			// one or more connections have data ready
			while(c = nm->getDataConnection()) {
				printf("[%d] Recv: %s", c->socket, c->getData());

				// send bytes back to the connection which sent them in
				sprintf(data, "(back) %s", c->getData());
				c->write(data);
				// send bytes to all clients with the specified data/value
				sprintf(data, "(toall) %s", c->getData());
				nm->write("port", c->get("port"), data);

				// we are finished with the data, pop it off the queue
				c->pop();
			}
		}
		else if(nm->isDel()) {
			// one or more connections have been dropped
			while(c = nm->getDelConnection()) {
				printf("[%d] Connection dropped.\n", c->socket);

				// stop tracking the connection
				nm->del(c);
			}

			// exit the example program
			break;
		}
		else {
			// nothing happened on the network
		}
	}

	// cleanup memory
	delete nm;

	// memory leak report
#ifdef _DEBUG
	_CrtDumpMemoryLeaks();
#endif // _DEBUG
}